//
//  SpeekViewController.m
//  YiXiProject
//
//  Created by iMac on 2019/7/25.
//  Copyright © 2019 iMac. All rights reserved.
//

#import "SpeekViewController.h"

#import "SpeakTopView.h"            // top-View

#import "STInputBar.h"              // 键盘

#import "SpeaksTableViewCell.h"     // cell

@interface SpeekViewController () <ClickSpeakTopBtnDelegate,UITableViewDelegate,UITableViewDataSource>

/** topView */
@property (nonatomic,strong) SpeakTopView *topSpeakView;
/** 键盘及输入框 */
@property (nonatomic,strong) STInputBar *inputBar;
/** table */
@property (nonatomic,strong) UITableView *table;
/** 存放发送的消息 */
@property (nonatomic,strong) NSMutableArray *strTextArr;

@end

@implementation SpeekViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = WhiteColor;
    
    _strTextArr = [[NSMutableArray alloc]init];
    
    [self creatTopSpeakView];  /** nav-View */
    
    [self.view addSubview:self.table];
    
    [self requestLoad];
    
    [self creatKeyBoard];
    
}   

-(void)requestLoad
{
    kWeakSelf(self);
    [HttpDatas requestImDataDataToken:@"f2e0c88f-7d32-3464-9cc5" user_id:@"36" success:^(id  _Nonnull json) {
        
        if([json isKindOfClass:[NSDictionary class]])
        {
            if([json[@"status"]integerValue] == 200)
            {
                NSDictionary *dicList = json[@"data"];
                
                NSArray *arrList = dicList[@"messages"];
                
                NSMutableArray *arrValue = [[NSMutableArray alloc]init];
                
                for (NSDictionary *dic in arrList)
                {
                    NSString *strId = [NSString stringWithFormat:@"%@",dic[@"id"]];
                    NSString *type = [NSString stringWithFormat:@"%@",dic[@"type"]];
                    NSString *mess = [NSString stringWithFormat:@"%@",dic[@"message"]];
                    
                    NSDictionary *messDic = @{
                                              @"id":strId,
                                              @"type":type,
                                              @"message":mess
                                              };
                    
                    [arrValue addObject:messDic];
                }
                
                weakself.strTextArr = arrValue;
                
                [weakself.topSpeakView.speakHeadImg sd_setImageWithURL:[NSURL URLWithString:dicList[@"photo"]] placeholderImage:nil];
                weakself.topSpeakView.nameL.text = dicList[@"name"];
                
                [weakself.table reloadData];
            }
        }
        
    } failure:^(NSError * _Nonnull err) {
        
    }];
    
    
//    NSDictionary *dic = @{
//                          @"ReContent":@"大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅",
//                          @"TypeId":@"0"
//                          };
//
//    NSDictionary *dic1 = @{
//                          @"ReContent":@"大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅大帅",
//                          @"TypeId":@"1"
//                          };
//
//    [_strTextArr addObject:dic];
//    [_strTextArr addObject:dic1];
    
}

// topView 初始化
-(void)creatTopSpeakView
{
    _topSpeakView = [[SpeakTopView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, navCurentHeight+90)];
    _topSpeakView.backgroundColor = [UIColor whiteColor];
    _topSpeakView.delegate = self;
    [self.view addSubview:_topSpeakView];
}

#pragma mark -- ClickSpeakTopBtnDelegate
-(void)clickSpeakButtonTag:(NSInteger)tag
{
    switch (tag) {
        case 100:
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case 101:
            NSLog(@"我是右");
            break;
            
        default:
            break;
    }
}
// 聊天输入框
-(void)creatKeyBoard
{
    _inputBar = [STInputBar inputBar];
    _inputBar.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height-_inputBar.bounds.size.height);
    [_inputBar setFitWhenKeyboardShowOrHide:YES];
    _inputBar.placeHolder = @"请在此输入内容。。";
    [self.view addSubview:_inputBar];
    
    // 发送消息 获取内容
    kWeakSelf(self);
    _inputBar.sendDidClickedHandler = ^(NSString *string) {
        
        if([string isEqualToString:@""] || string.length == 0)
        {
            return ;
        }
        else
        {
            weakself.inputBar.textView.text = @"";
            
            NSDictionary *dic = @{
                                  @"id":@"36",
                                  @"type":@"1",
                                  @"message":string
                                  };
            
            [weakself.strTextArr addObject:dic];
            [weakself.table reloadData];
            
            [weakself quXiaoEdit];
        }
    };
}

// 初始化table
-(UITableView *)table
{
    if(!_table)
    {
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topSpeakView.frame.size.height, SCREEN_WIDTH, SCREEN_HEIGHT-self.topSpeakView.frame.size.height-WD_TabBarHeight) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.backgroundColor = WhiteColor;
        _table.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        UITapGestureRecognizer *tapp = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buEdit)];
        [_table addGestureRecognizer:tapp];
    }
    return _table;
}

// 行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _strTextArr.count;
}

// 每行高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 设置文字属性 要和label的一致
    NSDictionary *attrs = @{NSFontAttributeName : [UIFont systemFontOfSize:16]};
    CGSize maxSize = CGSizeMake(SCREEN_WIDTH/2, MAXFLOAT);
    
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
    // 计算文字占据的高度
    CGSize size = [_strTextArr[indexPath.row][@"message"] boundingRectWithSize:maxSize options:options attributes:attrs context:nil].size;
    
    //当你是把获得的高度来布局控件的View的高度的时候.size转化为ceilf(size.height)。
    return  ceilf(size.height+25);
}

// 每行内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellid = @"cellid";
    
    SpeaksTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    
    if(!cell)
    {
        cell = [[SpeaksTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
    }
    
    cell.label.text = _strTextArr[indexPath.row][@"message"];
    [self setLineSpace:5.0f withText:cell.label.text inLabel:cell.label];
    
    // 获取文字部分尺寸
    NSDictionary *attrs = @{NSFontAttributeName : [UIFont systemFontOfSize:16]};
    CGSize maxSize = CGSizeMake(SCREEN_WIDTH/2, MAXFLOAT);
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
    // 计算文字占据的高度
    CGSize size = [_strTextArr[indexPath.row][@"message"] boundingRectWithSize:maxSize options:options attributes:attrs context:nil].size;
    
    //当你是把获得的高度来布局控件的View的高度的时候.size转化为ceilf(size.height)。
    NSInteger heightC = ceilf(size.height+50);
    
    // 获取文字宽度
    CGSize sizeToFit = [_strTextArr[indexPath.row][@"message"] sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(SCREEN_WIDTH/3*2, heightC-10) lineBreakMode:NSLineBreakByWordWrapping]; //此处的换行类型（lineBreakMode）可根据自己的实际情况进行设置
    
    // [_strTextArr[indexPath.row][@"TypeId"] integerValue] == 0 为自己发送的消息靠右边显示，否则在左边显示
    if([_strTextArr[indexPath.row][@"type"] integerValue] == 1)
    {
        cell.button.backgroundColor = ColorAlphe(51,153,255, 1);
        cell.label.textColor = WhiteColor;
        
        cell.button.sd_layout.rightSpaceToView(cell.contentView, 15).topSpaceToView(cell.contentView, 5).widthIs(sizeToFit.width+30).bottomSpaceToView(cell.contentView, 5);
    }
    else
    {
        cell.button.backgroundColor = ColorAlphe(210, 210, 210, 1);
        cell.label.textColor = BlackColor;
        
        cell.button.sd_layout.leftSpaceToView(cell.contentView, 15).topSpaceToView(cell.contentView, 5).widthIs(sizeToFit.width+30).bottomSpaceToView(cell.contentView, 5);
    }
    
    return cell;
}

// 行间距
-(void)setLineSpace:(CGFloat)lineSpace withText:(NSString *)text inLabel:(UILabel *)label{
    if (!text || !label) {
        return;
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpace;  //设置行间距
    paragraphStyle.lineBreakMode = label.lineBreakMode;
    paragraphStyle.alignment = label.textAlignment;
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    label.attributedText = attributedString;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

-(void)buEdit
{
    [self quXiaoEdit];
}
// 退出编辑
-(void)quXiaoEdit
{
    [_inputBar resignFirstResponder];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
